
<!DOCTYPE HTML>
<html>
	<head>
		<meta charset="utf-8">
		<title>分类-聚码网-站长交易平台</title>
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
		<link rel="stylesheet" href="./public/static/index/bui/bui.css">
		<script src="./public/static/index/bui/zepto.js"></script>
		<script src="./public/static/index/bui/bui.js"></script>
		<link rel="icon" href="./public/favicon.ico">
		<!-- 聊天在线状态管理 -->
		<script src="./public/static/index/js/chat-status.js"></script>
		<!-- 添加图标字体支持 -->
		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
		<style>
            /* 图标字体样式 */
            .icon-home:before {
                content: "\f015";
                font-family: FontAwesome;
            }
            .icon-shoppingcart:before {
                content: "\f07a";
                font-family: FontAwesome;
            }
            .icon-edit:before {
                content: "\f044";
                font-family: FontAwesome;
            }
            .icon-list:before {
                content: "\f03a";
                font-family: FontAwesome;
            }
            /* 确保图标显示 */
            [class^="icon-"], [class*=" icon-"] {
                font-family: FontAwesome;
                font-style: normal;
                font-weight: normal;
                display: inline-block;
                text-decoration: inherit;
            }
            body {
                margin: 0;
                padding: 0;
                display: flex;
                flex-direction: column;
                min-height: 100vh;
            }
            main {
                flex: 1;
                overflow: hidden;
                height: calc(100vh - 100px); /* 减去底部导航的高度 */
                background-color: #f3f5f8;
                display: flex;
            }
            .bui-tab-wrap {
                display: flex;
                width: 100%;
                height: 100%;
                overflow: hidden;
            }
            #tabSideNav {
                width: 100px;
                min-width: 100px;
                height: 100%;
                overflow-y: auto;
                overflow-x: hidden;
                -webkit-overflow-scrolling: touch;
                background-color: #f8f8f8;
                flex-shrink: 0;
                padding: 0 !important;
                margin: 0 !important;
            }
            #tabSideNav ul,
            #tabSideNav.bui-list,
            #tabSideNav.bui-tab-sidenav {
                padding: 0 !important;
                margin: 0 !important;
                list-style: none !important;
            }
            #tabSideNav li,
            #tabSideNav li.bui-btn,
            #tabSideNav li.category-item,
            #tabSideNav .bui-list li,
            #tabSideNav .bui-tab-sidenav li {
                width: 100% !important;
                max-width: 100% !important;
                padding: 6px 2px !important;
                margin: 0 !important;
                text-align: center !important;
                border-bottom: 1px solid #eee;
                cursor: pointer;
                transition: background-color 0.2s;
                white-space: nowrap !important;
                word-wrap: normal !important;
                word-break: keep-all !important;
                overflow: hidden !important;
                text-overflow: ellipsis !important;
                font-size: 12px !important;
                line-height: 1.2 !important;
                box-sizing: border-box !important;
                display: block !important;
                min-height: 28px !important;
                height: auto !important;
            }
            #tabSideNav li *,
            #tabSideNav li.category-item *,
            #tabSideNav .bui-list li *,
            #tabSideNav .bui-tab-sidenav li * {
                white-space: nowrap !important;
                word-break: keep-all !important;
                word-wrap: normal !important;
                overflow: hidden !important;
                text-overflow: ellipsis !important;
                display: inline !important;
            }
            #tabSideNav li.active {
                background-color: #fff;
                color: #ff0057;
                border-left: 3px solid #ff0057;
            }
            #tabSide {
                flex: 1;
                height: 100%;
                overflow-y: auto;
                overflow-x: hidden;
                -webkit-overflow-scrolling: touch;
                background-color: #fff;
            }
            footer {
                background-color: #fff;
                position: fixed;
                bottom: 0;
                left: 0;
                width: 100%;
                z-index: 1000;
            }
            .titleHidden{
                width: 100%;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
            }
            .bui-nav>.active {
    color: #f9342a;
    background: #fff;
}
.bui-thumbnail img{
    width: 100px;
    float: left;
    height: 100px;
}
.bui-nav{
    padding-bottom:2px;
}
        </style>
	</head>
	<body>
        
<div class="bui-page">
	<main>
        <div class="bui-tab-wrap">
            <ul id="tabSideNav" class="bui-list bui-tab-sidenav">
                <!-- 分类菜单将通过API动态加载 -->
                <li class='bui-btn' style="text-align: center; color: #999;">加载中...</li>
            </ul>
              <div id="tabSide">
                  <div id="categoryContentList">
                    <!-- 分类内容将通过API动态加载 -->
                    <div id="loading" style="padding: 20px; text-align: center; color: #999;">
                        <div>正在加载分类数据...</div>
                    </div>
                  </div>
              </div>
          </div>
	</main>
	<footer>
		<ul id="tabFootNav" class="bui-nav">
            <li id="homeGo" class="bui-btn bui-box-vertical">
                <a href="./index.html" style="display: flex; flex-direction: column; align-items: center; text-decoration: none; color: inherit;">
                    <i class="icon-home"></i>
                    <div class="span1">首页</div>
                </a>
            </li>
            <li id="classifyGo" class="bui-btn bui-box-vertical">
                <a href="./clsssify.html" style="display: flex; flex-direction: column; align-items: center; text-decoration: none; color: inherit;">
                    <i class="icon-list"></i>
                    <div class="span1">分类</div>
                </a>
            </li>
            <li id="shopCartGo" class="bui-btn bui-box-vertical">
                <a href="./shopCart.html" style="display: flex; flex-direction: column; align-items: center; text-decoration: none; color: inherit;">
                    <i class="icon-shoppingcart"></i>
                    <div class="span1">购物车</div>
                </a>
            </li>
            <li id="orderQueryGo" class="bui-btn bui-box-vertical">
                <a href="./orderQuery.html" style="display: flex; flex-direction: column; align-items: center; text-decoration: none; color: inherit;">
                    <i class="icon-edit"></i>
                    <div class="span1">订单</div>
                </a>
            </li>
            <!-- <li id="kflinksGo" class="bui-btn bui-box-vertical"><i class="icon-chat"></i>
                <div class="span1">客服</div>
            </li> -->
        </ul>
	</footer>
</div>

<script>
// API地址
var API_BASE_URL = "https://api.sc123.shop/";
var CATEGORY_API = API_BASE_URL + "/api/v1/index/get_category";
var GOODS_LIST_API = API_BASE_URL + "/api/v1/index/goods_list";

// 设置聊天状态管理的API地址
if (window.ChatStatus) {
    window.ChatStatus.setApiBaseUrl(API_BASE_URL);
}

var categoryList = [];
var allGoodsList = []; // 存储所有商品数据
var currentCategoryId = null;
var tab = null;

// 加载分类列表
function loadCategoryList() {
    console.log("开始加载分类列表:", CATEGORY_API);
    
    var xhr = new XMLHttpRequest();
    xhr.open('POST', CATEGORY_API, true);
    xhr.timeout = 10000;
    
    xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
            try {
                var response = JSON.parse(xhr.responseText);
                console.log("分类数据:", response);
                if (response && response.code === 200 && response.data) {
                    categoryList = response.data;
                    renderCategoryMenu(response.data);
                    // 加载所有商品
                    loadAllGoods(function() {
                        // 所有商品加载完成后，滚动到第一个分类
                        if (response.data.length > 0) {
                            isManualClick = true;
                            updateActiveCategory(0, response.data[0].id);
                            setTimeout(function() {
                                scrollToCategory(response.data[0].id);
                                isManualClick = false;
                            }, 300);
                        }
                    });
                } else {
                    console.error("获取分类列表失败:", response);
                    $("#tabSideNav").html('<li class="bui-btn" style="text-align: center; color: #f00;">加载失败</li>');
                }
            } catch (e) {
                console.error("解析分类数据失败:", e);
                $("#tabSideNav").html('<li class="bui-btn" style="text-align: center; color: #f00;">数据解析失败</li>');
            }
        } else {
            console.error("请求分类列表失败，状态码:", xhr.status);
            $("#tabSideNav").html('<li class="bui-btn" style="text-align: center; color: #f00;">请求失败</li>');
        }
    };
    
    xhr.onerror = function() {
        console.error("请求分类列表出错");
        $("#tabSideNav").html('<li class="bui-btn" style="text-align: center; color: #f00;">网络错误</li>');
    };
    
    xhr.ontimeout = function() {
        console.error("请求分类列表超时");
        $("#tabSideNav").html('<li class="bui-btn" style="text-align: center; color: #f00;">请求超时</li>');
    };
    
    xhr.send();
}

// 加载所有商品
function loadAllGoods(callback) {
    console.log("开始加载所有商品:", GOODS_LIST_API);
    
    var xhr = new XMLHttpRequest();
    xhr.open('POST', GOODS_LIST_API, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.timeout = 15000;
    
    xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
            try {
                var response = JSON.parse(xhr.responseText);
                console.log("所有商品数据:", response);
                if (response && response.code === 200 && response.data) {
                    allGoodsList = response.data;
                    // 将所有商品按分类ID分组并渲染
                    renderAllCategoryGoods();
                    if (callback) callback();
                } else {
                    console.error("获取商品列表失败:", response);
                    if (callback) callback();
                }
            } catch (e) {
                console.error("解析商品数据失败:", e);
                if (callback) callback();
            }
        } else {
            console.error("请求商品列表失败，状态码:", xhr.status);
            if (callback) callback();
        }
    };
    
    xhr.onerror = function() {
        console.error("请求商品列表出错");
        if (callback) callback();
    };
    
    xhr.ontimeout = function() {
        console.error("请求商品列表超时");
        if (callback) callback();
    };
    
    xhr.send();
}

// 渲染所有分类的商品
function renderAllCategoryGoods() {
    if (!allGoodsList || allGoodsList.length === 0) {
        console.warn("没有商品数据");
        return;
    }
    
    // 按分类ID分组商品
    var goodsByCategory = {};
    allGoodsList.forEach(function(item) {
        var categoryId = item.category_id;
        if (!goodsByCategory[categoryId]) {
            goodsByCategory[categoryId] = [];
        }
        goodsByCategory[categoryId].push(item);
    });
    
    // 为每个分类渲染商品
    categoryList.forEach(function(category) {
        var categoryId = category.id;
        var categoryContentId = "category_" + categoryId;
        var categoryGoods = goodsByCategory[categoryId] || [];
        
        if (categoryGoods.length > 0) {
            renderCategoryGoods(categoryContentId, categoryGoods);
        } else {
            $("#" + categoryContentId).html('<div style="padding: 20px; text-align: center; color: #999;">暂无商品</div>');
        }
    });
    
    console.log("所有分类商品渲染完成");
}

// HTML转义函数
function escapeHtml(text) {
    if (!text) return '';
    var map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return String(text).replace(/[&<>"']/g, function(m) { return map[m]; });
}

// 渲染分类菜单
function renderCategoryMenu(categories) {
    var navHtml = "";
    var contentHtml = "";
    
    categories.forEach(function(category, index) {
        // 处理分类名称：最多显示5个字，超过则截断
        var categoryName = category.category_name || '';
        var displayName = categoryName;
        if (categoryName.length > 5) {
            displayName = categoryName.substring(0, 5);
        }
        
        // 左侧导航菜单 - 直接显示文本，不包装span
        navHtml += '<li class="category-item' + (index === 0 ? ' active' : '') + '" data-category-id="' + category.id + '" data-category-index="' + index + '" data-category-name="' + escapeHtml(category.category_name) + '" title="' + escapeHtml(categoryName) + '" style="white-space: nowrap !important; word-break: keep-all !important; overflow: hidden !important; text-overflow: ellipsis !important;">' + escapeHtml(displayName) + '</li>';
        
        // 右侧内容区域 - 使用带ID的容器，方便滚动定位
        contentHtml += '<div id="category_' + category.id + '" class="category-content" data-category-id="' + category.id + '" data-category-index="' + index + '" data-category-name="' + category.category_name + '" style="min-height: 50px; padding: 10px 0;">' +
            '<div style="padding: 20px; text-align: center; color: #999;">加载中...</div>' +
            '</div>';
    });
    
    $("#tabSideNav").html(navHtml);
    $("#categoryContentList").html(contentHtml);
    
    // 初始化滚动同步
    initScrollSync(categories);
    
    // 绑定点击事件
    $("#tabSideNav li").on("click", function(e) {
        e.preventDefault();
        var categoryId = $(this).attr("data-category-id");
        var categoryIndex = $(this).attr("data-category-index");
        
        // 阻止滚动同步触发
        isManualClick = true;
        
        // 更新激活状态
        updateActiveCategory(categoryIndex, categoryId);
        
        // 直接滚动到对应位置（商品已经加载完毕）
        scrollToCategory(categoryId);
        
        setTimeout(function() {
            isManualClick = false;
        }, 300);
    });
}

var isManualClick = false; // 标记是否是手动点击
var isScrolling = false; // 标记是否正在滚动

// 初始化滚动同步
function initScrollSync(categories) {
    var $navList = $("#tabSideNav");
    var $contentArea = $("#tabSide");
    
    // 监听左侧分类列表滚动
    var navScrollTimer = null;
    $navList.on('scroll', function() {
        if (isManualClick || isScrolling) return;
        
        // 防抖处理
        clearTimeout(navScrollTimer);
        navScrollTimer = setTimeout(function() {
            syncNavToContent($navList, $contentArea);
        }, 100);
    });
    
    // 监听右侧商品列表滚动
    var contentScrollTimer = null;
    $contentArea.on('scroll', function() {
        if (isManualClick || isScrolling) return;
        
        // 防抖处理
        clearTimeout(contentScrollTimer);
        contentScrollTimer = setTimeout(function() {
            syncContentToNav($contentArea, $navList);
        }, 100);
    });
}

// 同步左侧导航到右侧内容（左侧滚动时）
function syncNavToContent($navList, $contentArea) {
    var scrollTop = $navList.scrollTop();
    var items = $navList.find('li');
    var activeItem = null;
    var minDistance = Infinity;
    
    // 找到当前在可视区域顶部或最接近顶部的分类项
    items.each(function() {
        var $item = $(this);
        var itemElement = $item[0];
        var itemTop = itemElement.offsetTop; // 相对于父容器的位置
        var itemHeight = itemElement.offsetHeight;
        var itemBottom = itemTop + itemHeight;
        
        // 计算分类项相对于可视区域的位置
        var viewTop = scrollTop;
        var viewBottom = scrollTop + $navList.height();
        
        // 如果分类项在可视区域内，或者最接近顶部
        if (itemTop <= viewTop + 30) { // 允许30px的容差
            var distance = viewTop - itemTop;
            if (distance >= -30 && distance < minDistance) {
                minDistance = distance;
                activeItem = $item;
            }
        }
    });
    
    // 如果没找到，找最接近顶部的
    if (!activeItem) {
        items.each(function() {
            var $item = $(this);
            var itemTop = $item[0].offsetTop;
            var distance = Math.abs(scrollTop - itemTop);
            
            if (distance < minDistance) {
                minDistance = distance;
                activeItem = $item;
            }
        });
    }
    
    if (activeItem) {
        var categoryId = activeItem.attr("data-category-id");
        var currentActiveId = $navList.find('li.active').attr("data-category-id");
        
        if (categoryId !== currentActiveId) {
            isScrolling = true;
            var categoryIndex = activeItem.attr("data-category-index");
            
            updateActiveCategory(categoryIndex, categoryId);
            scrollToCategory(categoryId);
            
            setTimeout(function() {
                isScrolling = false;
            }, 400);
        }
    }
}

// 同步右侧内容到左侧导航（右侧滚动时）
function syncContentToNav($contentArea, $navList) {
    var scrollTop = $contentArea.scrollTop();
    var contents = $contentArea.find('.category-content');
    var activeContent = null;
    var minDistance = Infinity;
    var viewTop = scrollTop;
    var viewHeight = $contentArea.height();
    
    // 找到当前在可视区域顶部或最接近顶部的分类内容
    contents.each(function() {
        var $content = $(this);
        var contentElement = $content[0];
        var contentTop = contentElement.offsetTop; // 相对于父容器的位置
        var contentHeight = contentElement.offsetHeight;
        var contentBottom = contentTop + contentHeight;
        
        // 如果分类内容在可视区域顶部附近（允许100px容差）
        if (contentTop <= viewTop + 100) {
            var distance = viewTop - contentTop;
            if (distance >= -100 && distance < minDistance) {
                minDistance = distance;
                activeContent = $content;
            }
        }
    });
    
    // 如果没找到，找最接近顶部的
    if (!activeContent) {
        contents.each(function() {
            var $content = $(this);
            var contentTop = $content[0].offsetTop;
            var distance = Math.abs(scrollTop - contentTop);
            
            if (distance < minDistance) {
                minDistance = distance;
                activeContent = $content;
            }
        });
    }
    
    if (activeContent) {
        var categoryId = activeContent.attr("data-category-id");
        var currentActiveId = $navList.find('li.active').attr("data-category-id");
        
        if (categoryId !== currentActiveId) {
            isScrolling = true;
            var categoryIndex = activeContent.attr("data-category-index");
            updateActiveCategory(categoryIndex, categoryId);
            
            // 滚动左侧分类到可见位置（居中显示）
            var $navItem = $navList.find('li[data-category-id="' + categoryId + '"]');
            if ($navItem.length > 0) {
                var navScrollTop = $navList.scrollTop();
                var navItemElement = $navItem[0];
                var navItemTop = navItemElement.offsetTop;
                var navItemHeight = navItemElement.offsetHeight;
                var navViewHeight = $navList.height();
                
                // 计算目标滚动位置，使分类项在可视区域居中
                var targetScrollTop = navItemTop - navViewHeight / 2 + navItemHeight / 2;
                
                // 限制滚动范围
                var maxScrollTop = $navList[0].scrollHeight - navViewHeight;
                targetScrollTop = Math.max(0, Math.min(targetScrollTop, maxScrollTop));
                
                $navList.animate({
                    scrollTop: targetScrollTop
                }, 300);
            }
            
            setTimeout(function() {
                isScrolling = false;
            }, 400);
        }
    }
}

// 更新激活的分类
function updateActiveCategory(index, categoryId) {
    $("#tabSideNav li").removeClass("active");
    $("#tabSideNav li[data-category-id='" + categoryId + "']").addClass("active");
}

// 滚动到指定的分类内容区域
function scrollToCategory(categoryId) {
    var $targetContent = $("#category_" + categoryId);
    if ($targetContent.length === 0) {
        console.warn("找不到分类内容:", categoryId);
        return;
    }
    
    var $contentArea = $("#tabSide");
    if ($contentArea.length === 0) {
        console.warn("找不到内容区域");
        return;
    }
    
    var contentElement = $targetContent[0];
    var contentAreaElement = $contentArea[0];
    
    // 等待DOM更新完成
    setTimeout(function() {
        // 计算元素相对于滚动容器的位置
        var contentTop = 0;
        var element = contentElement;
        
        // 方法1：遍历offsetParent计算位置
        while (element && element !== contentAreaElement && element !== document.body) {
            contentTop += element.offsetTop;
            element = element.offsetParent;
        }
        
        // 方法2：如果方法1失败，使用jQuery的position方法
        if (contentTop === 0 || element === document.body) {
            var position = $targetContent.position();
            if (position && position.top !== undefined) {
                contentTop = position.top + $contentArea.scrollTop();
            }
        }
        
        // 方法3：如果还是失败，使用offset计算
        if (contentTop === 0) {
            try {
                var targetOffset = $targetContent.offset();
                var containerOffset = $contentArea.offset();
                if (targetOffset && containerOffset) {
                    contentTop = targetOffset.top - containerOffset.top + $contentArea.scrollTop();
                }
            } catch (e) {
                console.warn("offset计算失败:", e);
            }
        }
        
        var targetScrollTop = contentTop - 10; // 留10px边距
        
        // 限制滚动范围
        var maxScrollTop = Math.max(0, contentAreaElement.scrollHeight - $contentArea.height());
        targetScrollTop = Math.max(0, Math.min(targetScrollTop, maxScrollTop));
        
        console.log("滚动到分类:", categoryId, "目标位置:", targetScrollTop, "当前滚动:", $contentArea.scrollTop(), "内容位置:", contentTop);
        
        // 使用scrollTop直接设置
        contentAreaElement.scrollTop = targetScrollTop;
        
        // 验证滚动是否成功
        setTimeout(function() {
            var actualScrollTop = $contentArea.scrollTop();
            if (Math.abs(actualScrollTop - targetScrollTop) > 20) {
                console.warn("滚动位置不准确，重新调整。实际:", actualScrollTop, "目标:", targetScrollTop);
                // 重新计算
                var newContentTop = 0;
                var newElement = contentElement;
                while (newElement && newElement !== contentAreaElement && newElement !== document.body) {
                    newContentTop += newElement.offsetTop;
                    newElement = newElement.offsetParent;
                }
                if (newContentTop > 0) {
                    contentAreaElement.scrollTop = Math.max(0, newContentTop - 10);
                }
            }
        }, 100);
    }, 50);
}

// 移除原来的Tab初始化，使用自定义滚动同步

// 此函数已废弃，商品在页面加载时一次性加载完毕

// 渲染分类商品列表
function renderCategoryGoods(containerId, goodsList) {
    if (!goodsList || goodsList.length === 0) {
        $("#" + containerId).html('<div style="padding: 20px; text-align: center; color: #999;">暂无商品</div>');
        return;
    }
    
    var html = '<ul class="bui-list bui-list-thumbnail">';
    
    goodsList.forEach(function(item) {
        // 处理图片URL
        var imgUrl = "";
        if (item.goods_img) {
            var firstImg = item.goods_img.split(';')[0].trim();
            if (firstImg.indexOf('http') === 0) {
                imgUrl = firstImg;
            } else {
                imgUrl = API_BASE_URL + firstImg;
            }
        } else {
            imgUrl = "https://via.placeholder.com/300x300?text=No+Image";
        }
        
        // 格式化价格
        var discountPrice = parseFloat(item.discount || 0).toFixed(2);
        var originalPrice = parseFloat(item.amount || 0).toFixed(2);
        
        html += '<li class="bui-btn bui-box goods-box" onclick="window.location.href=\'./goodsInfo.html?id=' + item.id + '\'">' +
            '<div class="bui-thumbnail"><img src="' + imgUrl + '" alt="' + (item.goods_name || '商品') + '" onerror="this.src=\'https://via.placeholder.com/300x300?text=Error\'"></div>' +
            '<div class="span1">' +
            '<div class="nametj" style="color: #262626;font-size: 0.3rem;">' + (item.goods_name || '商品名称') + '</div>' +
            '<p class="item-text">' +
            '<font style="color: #fb0247;font-weight: bolder;">￥' + discountPrice + '</font>';
        
        // 如果有原价且原价大于现价，显示原价
        if (originalPrice && parseFloat(originalPrice) > parseFloat(discountPrice)) {
            html += ' <font style="color: #898989;font-weight: bolder;font-size: .2rem;text-decoration: line-through;">￥' + originalPrice + '</font>';
        }
        
        html += '</p>' +
            '</div>' +
            '</li>';
    });
    
    html += '</ul>';
    
    $("#" + containerId).html(html);
    
    // 初始化商品点击事件
    if (typeof bui !== 'undefined' && typeof bui.btn === 'function') {
        try {
            bui.btn({id:".bui-page",handle:".goods-box"}).load();
        } catch (e) {
            console.warn("bui.btn初始化失败:", e);
        }
    }
}

// 页面初始化
$(document).ready(function() {
    console.log("分类页面DOM加载完成");
    loadCategoryList();
});

bui.ready(function(){
    bui.btn({id:".bui-page",handle:".goods-box"}).load();
    $("#homeGo").on("click",function(e){
        e.preventDefault();
        window.location.href = "./index.html";
    });
    $("#classifyGo").on("click",function(e){
        e.preventDefault();
        window.location.href = "./clsssify.html";
    });
    $("#shopCartGo").on("click",function(e){
        e.preventDefault();
        window.location.href = "./shopCart.html";
    });
    $("#orderQueryGo").on("click",function(e){
        e.preventDefault();
        window.location.href = "./orderQuery.html";
    });
});
</script>
</body>
</html>